package de.upb.aquarium.api.objects;

import javax.media.opengl.GL;

import objimp.ObjImpScene;
import de.upb.aquarium.World;

public class TransparentObject extends General3DObject implements Comparable<TransparentObject> {

	private final ObjImpScene object;
	private float[] absolutePosition;


	public TransparentObject(GL gl, String filename, float scale) {
		object = new ObjImpScene(gl);
		object.load(filename, scale);
	}

	@Override
	public void paint(GL gl) {
		beforeRendering(gl);
		object.draw(gl);
		afterRendering(gl);
	}

	@Override
	protected void beforeRendering(GL gl) {
		// set to absolute position
		float[] tmpPos = getPosition();
		setPosition(new float[] {absolutePosition[0]+tmpPos[0], absolutePosition[1]+tmpPos[1], absolutePosition[2]+tmpPos[2]});
		super.beforeRendering(gl);
		// restore position
		setPosition(tmpPos);

		gl.glEnable(GL.GL_BLEND);
		gl.glDisable(GL.GL_CULL_FACE);
		gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
		gl.glDepthMask(false);
	}

	@Override
	protected void afterRendering(GL gl) {
		gl.glDisable(GL.GL_BLEND);
		//		gl.glEnable(GL.GL_CULL_FACE);
		gl.glDepthMask(true);
		super.afterRendering(gl);
	}

	public double getDistanceToCamera() {
		double[] camPos = World.getInstance().getCamera().getPosition().data;
		float[] centerOfBoundingBox = object.getCenterOfBoundingBox();
		float[] position = new float[] {
				absolutePosition[0] + centerOfBoundingBox[0],
				absolutePosition[1] + centerOfBoundingBox[1],
				absolutePosition[2] + centerOfBoundingBox[2]
		};
		double dx = position[0] - camPos[0];
		double dy = position[1] - camPos[1];
		double dz = position[2] - camPos[2];
		return Math.sqrt(dx*dx+dy*dy+dz*dz);
	}

	@Override
	public int compareTo(TransparentObject o) {
		double a = getDistanceToCamera();
		double b = o.getDistanceToCamera();
		if (a == b)
			return 0;
		return (a>b)?-1:1;
	}

	public void setAbsolutePosition(float[] absolutePosition) {
		float[] position = getPosition();
		this.absolutePosition = new float[] {
				absolutePosition[0] + position[0],
				absolutePosition[1] + position[1],
				absolutePosition[2] + position[2]
		};
	}
}
